﻿#include <QEventLoop>
#include "MainWindow.h"
#include "qtimer.h"
#include "qpushbutton.h"
#include "./ui_MainWindow.h"
#include "sroll_trigger/utils/utils.h"
#include "libdaq/device/base_device.h"
#include "sroll_trigger/connect_page/connect_page.h"
#include "sroll_trigger/scroll_mode_thread/scroll_mode_thread.h"

using namespace libdaq::device;
QThreadPool read_data_thread_pool_;  // 线程池
std::vector<std::shared_ptr<std::vector<float>>> ADC_Data_Buffer(4); // 连续采集数据缓存
std::vector<bool> ADCDataState = {false, false, false, false};

MainWindow::MainWindow(QWidget *parent)
  : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  qRegisterMetaType<std::vector<std::vector<float> > >("std::vector<std::vector<float>>");
  // 创建设备
  base_device_ = NewDevice();
  connect(ui->Connnectbutton, &QPushButton::clicked, this, &MainWindow::ClickConnectAction);
  connect(ui->StartADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStartADCCollectionAction);
  connect(ui->UpdateConfig, &QPushButton::clicked, this, &MainWindow::ClickUpdateConfig);
  connect(ui->OnceCollection, &QPushButton::clicked, this, &MainWindow::ClickSoftwareTrigger);
  connect(ui->StopADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStopADCCollection);

  InitWaveWidget();

}

MainWindow::~MainWindow() {
  delete ui;
    if (scroll_mode_adc_thread_ != nullptr) {
        scroll_mode_adc_thread_->quit();
        scroll_mode_adc_thread_->deleteLater();
        scroll_mode_adc_thread_ = nullptr;
    }
}

void MainWindow::ConnectStatusSlot(bool status, ConnectPage::ConnectType type) {
  if (status) {
    if (!base_device_->InitializeDevice()) {
      qWarning(u8"初始化设备失败，请检查配置参数是否存在错误");
      return;
    }
    if (!base_device_->ConnectedDevice()) {
      qWarning(u8"发送连接设备命令失败");
      return;
    }
  }
}

void MainWindow::ClickConnectAction() {
  ConnectPage connect_page(base_device_, nullptr);
  // 初始化连接界面
  if (connect_page_.isNull()) {
    connect_page_.reset(new ConnectPage(base_device_));
    connect_page_->setModal(false);
    connect(connect_page_.get(), &ConnectPage::ConnectStatus, this, &MainWindow::ConnectStatusSlot);
  }
  connect_page_->InitParams(base_device_);
  connect_page_->show();
}

void MainWindow::ClickStartADCCollectionAction() {
  is_start_adc_collection_ = true;
  ScrollCollection();
  qInfo(u8"启动ADC采集成功");
}

void MainWindow::ClickUpdateConfig() {
  // 采样率 1M
  auto legal_sample_rate = base_device_->GetADCLegalSampleRate();
  if (!base_device_->ConfigADCSampleRate(LockzhinerADCSampleRate::ADCSampleRate_1_M)) {
    qWarning(u8"采样率配置失败");
  }
  // 电压量程 10V
  if (!base_device_->ConfigADCVoltage(LockzhinerADCVoltage::ADCVoltage_1V)) {
    qWarning(u8"电压量程配置失败");
  }
  // 2通道使能
  if (!base_device_->ConfigADCChannel(0x03)) {
    qWarning(u8"ADC2通道配置失败");
  }
  // 触发电平 0mv
  uint32_t level = 0;
  // 双边缘触发 自动触发 软件触发
  auto type = static_cast<LockzhinerADCTriggerType>(LockzhinerADCTriggerType::Normal);
  auto mode = static_cast<LockzhinerADCTriggerMode>(LockzhinerADCTriggerMode::Automatic);
  auto channel = static_cast<LockzhinerADCChannel>(LockzhinerADCChannel::ADCChannelAINNone);
  if (!base_device_->ConfigADCTrigger(type, mode, channel, level)) {
    qWarning(u8"DAQ控制器配置ADC触发失败");
  }

  // 长度 4920个点
  if (!base_device_->ConfigADCTriggerLength(4920)) {
    qWarning(u8"触发长度配置失败");
  }
  // 超时 100ms
  if (!base_device_->ConfigTriggerTimeout(100)) {
    qWarning(u8"超时时间配置失败");
  }

  // AC/DC 设置为DC
  uint8_t enable = 0x0F;
  if (!base_device_->ConfigACDC(enable)) {
    qWarning("配置AC/DC失败");
    return;
  }

  qInfo(u8"下发配置成功");
}

void MainWindow::ClickSoftwareTrigger() {
  if (!base_device_->ConfigADCTriggerSource
    (static_cast<uint8_t>(libdaq::device::DAQADCTriggerSource::TriggerSourceSoftware))) {
    qWarning(u8"软件触发失败");
    return;
  }
  qInfo(u8"软件触发成功");
}

void MainWindow::ClickStopADCCollection() {
  is_start_adc_collection_ = false;
  if (!base_device_->StopADCCollection()) {
    qWarning(u8"停止ADC采集失败");
    return;
  }
  if (scroll_mode_adc_thread_ != nullptr) {
      scroll_mode_adc_thread_->quit();
      scroll_mode_adc_thread_->deleteLater();
      scroll_mode_adc_thread_ = nullptr;
  }
  qInfo(u8"停止ADC采集成功");

}

void MainWindow::InitWaveWidget() {
  QVector<Qt::GlobalColor> channel_color_ = { // 通道颜色
    Qt::red, Qt::green, Qt::cyan, Qt::blue
  };
  base_wave_widget_ = QSharedPointer<BaseWaveWidget>::create();
  base_wave_widget_->InitChannel(2, channel_color_); // 初始化通道数


  QVector<bool> state = {true, true, true, true};
  base_wave_widget_->InitChannelState(state); // 初始化各通道数据显示状态
  ui->stackedWidget->addWidget(base_wave_widget_.get());
  ui->stackedWidget->setCurrentWidget(base_wave_widget_.get());
}


void MainWindow::ScrollCollection() {
    if (!is_start_adc_collection_) {
        return;
    }

    is_start_adc_collection_ = true;
    is_roll_mode_ = true;

    if (!base_device_->StopADCCollection()) {
        qWarning(u8"尝试停止ADC采集失败");
    }

    if (!base_device_->StartADCCollection()) {
        qWarning(u8"开始ADC采集失败");
    }

    if (scroll_mode_adc_thread_ != nullptr) {
        scroll_mode_adc_thread_->quit();
        scroll_mode_adc_thread_->deleteLater();
        scroll_mode_adc_thread_ = nullptr;
    }
    scroll_mode_adc_thread_ = QSharedPointer<ScrollModeADCThread>::create(base_device_);
    connect(scroll_mode_adc_thread_.get(), &ScrollModeADCThread::SendData, this, &MainWindow::UpdatePlotData);
    scroll_mode_adc_thread_->start();
}

void MainWindow::UpdatePlotData(const std::vector<std::vector<float> > &data) {


    // 判断数据是否为空
    bool is_empty = true;
    for (const auto &i: data) {
        if (!i.empty()) {
            is_empty = false;
            break;
        }
    }

    if (is_empty) {
      return;
    }

    auto trigger_type = base_device_->GetCurrentTriggerType();
    if (trigger_type != LockzhinerADCTriggerType::Normal) {
        // 触发类型不为滚动模式 清空之前的数据
        base_wave_widget_->Clear();
    }
    // 添加数据到图表
    for (int i = 0; i < data.size(); ++i) {
        for (int j = 0; j < data.at(i).size(); ++j) {
            base_wave_widget_->AddData(i, data[i][j]);
        }
    }

    // 更新图表
    UpdateAutoScale(trigger_type == LockzhinerADCTriggerType::Normal);
    base_wave_widget_->replot(QCustomPlot::rpQueuedReplot);

}
void MainWindow::UpdateAutoScale(bool open_scroll) {
        // 寻找数据目前最长长度
    uint32_t data_length_max = 0;
    for (int i = 0; i < 2; ++i) {
        data_length_max = std::max(base_wave_widget_->graph(i)->data()->size(), int(data_length_max));
    }
    auto trigger_data_length = base_device_->GetCurrentDataLength();
    if (data_length_max > trigger_data_length) {
        base_wave_widget_->xAxis->setRange(data_length_max - trigger_data_length, data_length_max);
    } else {
        base_wave_widget_->xAxis->setRange(0, trigger_data_length);
    }

}
